package com.example.ecas.controller;

import com.example.ecas.common.CommonResponse;
import com.example.ecas.persistence.AccountMapper;
import com.example.ecas.persistence.DisRtagMapper;
import com.example.ecas.pojo.DisRtag;
import com.example.ecas.service.SmsService;
import com.example.ecas.pojo.Account;
import com.example.ecas.service.EmailService;

import com.example.ecas.service.WordCloudService;
import com.example.ecas.utils.PythonExecutor;
import org.python.core.Py;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    private EmailService emailService;

    @Autowired
    public void setEmailService(EmailService emailService) {
        this.emailService = emailService;
    }


    // 用户账号密码登录
//    @CrossOrigin
    @PostMapping(value = "/login")
    @ResponseBody
    public CommonResponse<Object> login(@RequestBody Account reqAccount, HttpSession session) throws IOException, InterruptedException {


        if (reqAccount == null || reqAccount.getId() == null || reqAccount.getId().isEmpty()) {
            return CommonResponse.creatForError("请输入用户名");
        }
        if (reqAccount.getPassword() == null || reqAccount.getPassword().isEmpty()) {
            return CommonResponse.creatForError("请输入密码");
        }
        Account account = accountMapper.getAccount(reqAccount.getId());
        if (account == null) {
            return CommonResponse.creatForError("账号不存在");
        }
        if (!account.getPassword().equals(reqAccount.getPassword())) {
            return CommonResponse.creatForError("用户名或密码错误");
        }
        session.setAttribute("account", account);
        return CommonResponse.creatForSuccess("登录成功", account);

    }

    // 请求向指定手机号发送验证码（用于登录）
    @GetMapping(value = "/sms")
    @CrossOrigin
    public CommonResponse<Object> sendSmsForLogin(@RequestParam("phone") String phone, HttpSession session) {
        int authCode = 0;
        try {
            authCode = SmsService.sendSms(phone);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.creatForError("验证码发送失败");
        }
        // 获取发送验证码时的时间戳，用于验证码过期判断
        long timeStamp = System.currentTimeMillis();
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("authCode", Integer.toString(authCode));
        codeMap.put("timeStamp", String.valueOf(timeStamp));
        session.setAttribute("phone"+phone, codeMap);
        return CommonResponse.creatForSuccess("验证码发送成功");
    }

    // 短信验证码登录，若无账户则注册一个
    @PostMapping(value = "/smsLogin")
    public CommonResponse<Object> loginBySms(@RequestBody Account reqAccount, @RequestParam("authCode") String authCode, HttpSession session) {
        if (reqAccount == null || reqAccount.getPhone().trim().isEmpty()) {
            return CommonResponse.creatForError("请输入手机号");
        }
        if (authCode == null) {
            return CommonResponse.creatForError("请输入验证码");
        }
        reqAccount.setPhone(reqAccount.getPhone().trim());
        // 判断验证码是否过期
        Map<String, String> codeMap = (Map<String, String>) session.getAttribute("phone" + reqAccount.getPhone());
        try {
            // 超过300s后的验证码是过期验证码
            if (codeMap == null || ((System.currentTimeMillis() - Long.parseLong(codeMap.get("timeStamp"))) / 1000) > 300) {
                if (codeMap != null) {
                    // 删除验证码session
                    session.removeAttribute("phone" + reqAccount.getPhone());
                }
                return CommonResponse.creatForError("验证码不存在或已过期");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.creatForError("服务器错误");
        }
        if (!codeMap.get("authCode").equals(authCode)) {
            return CommonResponse.creatForError("验证码错误，请重新输入");
        }
        // 从前端传的reqAccount查找数据库里的对应的账号，找不到就创建一个
        Account account = accountMapper.getAccountByPhone(reqAccount.getPhone());

        if(account == null){
            Map<String, String> sessionAttributes = (Map<String, String>) session.getAttribute("phone" + reqAccount.getPhone());
            if (sessionAttributes == null) {
                return CommonResponse.creatForError("注册失败，请重新尝试");
            }

            String sauCode = sessionAttributes.get("authCode");

            // 如果和前端传来的验证码不一致，注册失败
            if (!sauCode.equals(authCode)){
                return CommonResponse.creatForError("注册失败，请重新尝试");
            }

            // 短信注册的用户id为手机号，密码默认为123456，默认权限为普通用户
            reqAccount.setId(reqAccount.getPhone());
            reqAccount.setPassword("123456");
            reqAccount.setAdmin(false);

            // 注册成功,将数据写入数据库
            accountMapper.insertNewAccount(reqAccount);

            // 更新account对象为新注册账号信息
            account = reqAccount;
            session.setAttribute("account", account);
            return CommonResponse.creatForSuccess("注册成功",account);
        }
        session.setAttribute("account", account);
        // 删除验证码session
        session.removeAttribute("phone" + reqAccount.getPhone());
        return CommonResponse.creatForSuccess("登录成功", account);
    }

    // 请求向指定邮箱发送验证码（用于登录）
    @GetMapping("/email")
    public CommonResponse<Object> sendEmailForLogin(@RequestParam("email") String email, HttpSession session){
        try {
            // 调用EmailService中的发送验证码方法
            String authCode = emailService.toUserEmailWithCode(email);

            // 获取发送验证码时的时间戳，用于验证码过期判断
            long timeStamp = System.currentTimeMillis();
            Map<String, String> codeMap = new HashMap<>();
            codeMap.put("authCode", authCode);
            codeMap.put("timeStamp", String.valueOf(timeStamp));
            session.setAttribute("email"+email, codeMap);

            return CommonResponse.creatForSuccess("验证码发送成功");
        } catch (MessagingException e) {
            // 发送邮件失败，返回错误状态码和消息
            return CommonResponse.creatForError("验证码发送失败");
        }
    }

    // 邮箱验证码登录，若无账户则注册一个
    @PostMapping("/emailLogin")
    public CommonResponse<Object> loginByEmail(@RequestBody Account reqAccount, @RequestParam("authCode") String authCode, HttpSession session) {
        if (reqAccount == null || reqAccount.getEmail().trim().isEmpty()) {
            return CommonResponse.creatForError("请输入邮箱");
        }
        if (authCode == null) {
            return CommonResponse.creatForError("请输入验证码");
        }
        reqAccount.setEmail(reqAccount.getEmail().trim());
        // 判断验证码是否过期
        Map<String, String> codeMap = (Map<String, String>) session.getAttribute("email" + reqAccount.getEmail());
        try {
            // 超过300s后的验证码是过期验证码
            if (codeMap == null || ((System.currentTimeMillis() - Long.parseLong(codeMap.get("timeStamp"))) / 1000) > 300) {
                if (codeMap != null) {
                    // 删除验证码session
                    session.removeAttribute("email" + reqAccount.getEmail());
                }
                return CommonResponse.creatForError("验证码不存在或已过期");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.creatForError("服务器错误");
        }
        if (!codeMap.get("authCode").equals(authCode)) {
            return CommonResponse.creatForError("验证码错误，请重新输入");
        }
        // 从前端传的reqAccount查找数据库里的对应的账号，找不到就创建一个
        Account account = accountMapper.getAccountByEmail(reqAccount.getEmail());
        if(account == null){
            Map<String, String> sessionAttributes = (Map<String, String>) session.getAttribute("email" + reqAccount.getEmail());
            if (sessionAttributes == null) {
                return CommonResponse.creatForError("注册失败，请重新尝试");
            }

            String sauCode = sessionAttributes.get("authCode");

            // 如果和前端传来的验证码不一致，注册失败
            if (!sauCode.equals(authCode)){
                return CommonResponse.creatForError("注册失败，请重新尝试");
            }

            // 邮箱注册的用户id为邮箱，密码默认为123456，默认权限为普通用户
            reqAccount.setId(reqAccount.getEmail());
            reqAccount.setPassword("123456");
            reqAccount.setAdmin(false);


            // 注册成功,将数据写入数据库
            accountMapper.insertNewAccount(reqAccount);

            // 更新account对象为新注册账号信息
            account = reqAccount;
            session.setAttribute("account", account);
            return CommonResponse.creatForSuccess("注册成功",account);
        }

        session.setAttribute("account", account);
        // 删除验证码session
        session.removeAttribute("email" + reqAccount.getEmail());
        return CommonResponse.creatForSuccess("登录成功", account);
    }

}

